﻿namespace FFF.Test.Application
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Abp.Dependency;
    using Abp.Runtime.Session;
    using Castle.Core.Logging;
    using Microsoft.AspNetCore.SignalR;
    using FFF.Test.Application.AppServices.PublicService.Sessions;
    using FFF.Test.Application.AppServices.PublicService.SignalRs;

    /// <summary>
    /// signalr连接类
    /// </summary>
    public class MyChatHub : Hub, ITransientDependency
    {
        /// <summary>
        /// 记录日志
        /// </summary>
        public ILogger Logger { get; set; }

        private readonly ISessionAppService _sessionAppservice;
        private readonly ISignalRAppService _signalAppservice;

        /// <summary>
        /// Initializes a new instance of the <see cref="MyChatHub"/> class.
        ///  signalr连接类
        /// </summary>
        /// <param name="sessionAppservice">session服务</param>
        /// <param name="signalAppservice">signalAppservice</param>
        public MyChatHub(ISessionAppService sessionAppservice, ISignalRAppService signalAppservice)
        {
            this.Logger = NullLogger.Instance;
            this._sessionAppservice = sessionAppservice;
            this._signalAppservice = signalAppservice;
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="message">消息内容</param>
        /// <returns>消息</returns>
        public async Task SendMessage(string message)
        {
            var userInfo = await this._sessionAppservice.GetCurrentUserInfo();
            await base.Clients.All.SendAsync("getMessage", $"{userInfo.UserName}上线了,并且说话了:{message}");
        }

        /// <summary>
        /// 客户进入链接调用
        /// </summary>
        /// <returns><see cref="Task"/> representing the asynchronous operation.</placeholder></returns>
        public override async Task OnConnectedAsync()
        {
            await base.OnConnectedAsync();
            var userInfo = await this._sessionAppservice.GetCurrentUserInfo();
            await this._signalAppservice.SetUserConId(userInfo.Id, base.Context.ConnectionId);
        }

        /// <summary>
        /// 未连接
        /// </summary>
        /// <param name="exception">异常</param>
        /// <returns>空</returns>
        public override async Task OnDisconnectedAsync(Exception exception)
        {
            await base.OnDisconnectedAsync(exception);
            var userInfo = await this._sessionAppservice.GetCurrentUserInfo();
            await this._signalAppservice.RemoveUserConId(userInfo.Id);
        }
    }
}
